﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Data;
using ClassLibrary1;
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        int CurrCol, CurrRow;
        Database db, _db;
        //List<Cm> cm0;
        string[] Msg = {"保存成功！"};
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string msg = Class1.Class2();
            //List<Cm> _cm = new List<Cm>();
            //List<Cm> _cm = Class1.GetCm();
           // MessageBox.Show(_cm[0].BarcodeName);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            textBox1.Focus();
            string djh = _db.ExecuteScalar(CommandType.Text, String.Format("select isnull(MAX(DocuNumber),'100000') + 1 from dbo.StoreDocu where YEAR(rq)={0} and MONTH(rq)={1}", dateTimePicker1.Value.Year.ToString(), dateTimePicker1.Value.Month.ToString())).ToString();
            sb.Append("declare @master int,@ItemId int;");
            sb.Append(String.Format(" INSERT INTO StoreDocu (typeId,rq,DocuNumber) values (1,'{0}','{1}') ;", dateTimePicker1.Text, djh.ToString()));
            sb.Append(" set @master = (select @@IDENTITY) ;");

            int len = dataGridView1.Rows.Count;
            for (int i = 0; i < len; i++)
            {
                if (dataGridView1[0, i].Value == null) continue;
                sb.Append(String.Format(" insert into storeItem (DocuStoreId, ProdCode, ProdNum) values (@master, '{0}',{1}) ;", dataGridView1[0, i].Value, dataGridView1[1, i].Value));
                sb.Append(" set @ItemId =  (select @@IDENTITY) ;");
                List<Cm> cm = Class1.GetCm();
                for (int j = 0; j < cm.Count; j++)
                {
                    if (dataGridView1.Rows[i].Cells["_" + cm[j].id.ToString()].Value != null)
                    {
                        if (dataGridView1.Rows[i].Cells["_" + cm[j].id.ToString()].Value.ToString().Length > 0)
                            sb.Append(String.Format(" insert into dbo.StoreItemDetail (StoreDocuId,ItemId,BarcodeId,num0) values (@master,@ItemId,'{0}',{1});", cm[j].id.ToString(), dataGridView1.Rows[i].Cells["_" + cm[j].id.ToString()].Value.ToString()));
                    }

                }

            }
            sb.Append(" select @master;");
            string id = _db.ExecuteScalar(CommandType.Text, sb.ToString()).ToString();
            MessageBox.Show(Msg[0]);
            DataBing(id);
            textBox5.Text = sb.ToString();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //dataGridView1.
        }

        private void Dv1EndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                CurrCol = e.ColumnIndex;
                CurrRow = e.RowIndex;
                listBox1.Top = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Bottom + dataGridView1.Top;
                listBox1.Left = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Left + dataGridView1.Left;
                listBox1.Visible = true;
                String _str = dataGridView1[0, CurrRow].Value.ToString();
                DataSet ds = db.ExecuteDataSet(CommandType.Text,  string.Format("select top 10 sphh,lsdj,sphh+' | '+spmc sp from yx_t_spdmb where sphh like '{0}%'", _str));

                listBox1.DataSource = ds.Tables[0].DefaultView;
                listBox1.DisplayMember = "sp";
                listBox1.ValueMember = "sphh";
                listBox1.Focus();
               // listBox1.SelectedIndex = 1; 
            }
        }

        private void Dv1MouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                
            }
        }

        private void Dv1Enter(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void Dv1MouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                //MessageBox.Show("End!");
                //listBox1.Visible = false;
            }
        }

        private void Listview1KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                
                listBox1.Visible = false;
                dataGridView1.CurrentCell = dataGridView1[1, CurrRow];
            };
           // MessageBox.Show(e.KeyValue.ToString());
        }

        private void SelectChange(object sender, EventArgs e)
        {
            //dataGridView1.Rows[CurrRow][CurrCol] = listBox1.SelectedValue;
            dataGridView1[0, CurrRow].Value = listBox1.SelectedValue.ToString();
            
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            db = DatabaseFactory.CreateDatabase("ConnectionString");
            _db = DatabaseFactory.CreateDatabase("Connection0");
            List<Cm> cm0 = Class1.GetCm();
            {
                for (int i = 0; i < cm0.Count; i++)
                {
                    DataGridViewColumn column = new DataGridViewTextBoxColumn();
                    column.DataPropertyName = "_" + cm0[i].id.ToString(); //绑定的列
                    column.Width = 28;
                    column.Name = "_" + cm0[i].id.ToString(); //列名
                    column.HeaderText = cm0[i].BarcodeName; //显示的标题
                    dataGridView1.Columns.Add(column);
                }
            }

           
        }

        private void CellOnforce(object sender, DataGridViewCellEventArgs e)
        {
            
           // CurrCol = e.ColumnIndex;
            //CurrRow = e.RowIndex;
           // MessageBox.Show(CurrCol.ToString());
        }

        private void List1Click(object sender, EventArgs e)
        {
            MessageBox.Show(listBox1.SelectedValue.ToString());
        }

        private void toolStripButton3_Click_1(object sender, EventArgs e)
        {
            try
            {
                //DataGridViewRow row = new DataGridViewRow();
                //row.CreateCells(dataGridView1);
                //dataGridView1.Rows.Insert(dataGridView1.Rows.Count - 1, row);
                DataTable dt = (DataTable)dataGridView1.DataSource;
                DataRow dr = dt.NewRow();
                dt.Rows.InsertAt(dr,1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            //dataGridView1.Rows.Insert(1, row);
           // dataGridView1.Rows[i].Cells.
        }

        private void TextKeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dataGridView1);
                row.Cells[0].Value = textBox4.Text;
                dataGridView1.Rows.Add(row);
                textBox4.Text = "";
            }
        }

        private void dv1KeyUp(object sender, KeyEventArgs e)
        {
            MessageBox.Show("T");
            if (dataGridView1.CurrentCell.ColumnIndex >= 3)
            {
                
                dataGridView1.CurrentRow.Cells[1].Value = 0;
                for (int i = 0; i < cm0.Count; i++)
                {
                   // dataGridView1.CurrentRow.Cells[1] = int.Parse(dataGridView1.CurrentRow.Cells[1].ToString()) + 
                }
            }
        }

        private void dv1KeyPress(object sender, KeyPressEventArgs e)
        {
            MessageBox.Show("T1");
        }

        private void LostForce(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 3)
            {
                dataGridView1.CurrentRow.Cells[1].Value = 0;
            }
        }
        private void DataBing(string id)
        {
            dataGridView1.AutoGenerateColumns = false;
            DataSet ds = _db.ExecuteDataSet(CommandType.Text, string.Format( "SELECT ItemId,ProdCode, ProdNum, price, sum FROM StoreItem WHERE (DocuStoreId = {0});SELECT  ItemId,StoreDocuId, BarcodeId, num0, num1 FROM StoreItemDetail WHERE (StoreDocuId = {0})", id));
            ds.Relations.Add("mxid", ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
            List<Cm> cm = Class1.GetCm();
            for (int i = 0; i < cm.Count; i++)
            {
                //初始化尺码组
                ds.Tables[0].Columns.Add(new DataColumn("_" + cm[i].id.ToString(), typeof(Int32)));
            }
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                DataRow r = ds.Tables[0].Rows[i];
                foreach (DataRow r0 in r.GetChildRows("mxid"))
                {

                    try
                    {
                        ds.Tables[0].Rows[i]["_" + r0["BarcodeId"].ToString()] = r0["num0"];

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        break;
                    }
                }
            }
            dataGridView1.DataSource = ds.Tables[0];
            dataGridView1.Columns[0].DataPropertyName = "ProdCode";
            dataGridView1.Columns[1].DataPropertyName = "ProdNum";
            dataGridView1.Columns[2].DataPropertyName = "price";
            dataGridView1.Refresh();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            DataBing("8");
        }
    }
}